package spittr.web;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import spittr.data.ISpitterRepository;
import spittr.data.Spitter;

@Controller
@RequestMapping("/spitter")
public class SpitterController
{
    private ISpitterRepository spitterRepository;

    @Autowired
    public SpitterController(ISpitterRepository spitterRepository)
    {
        this.spitterRepository = spitterRepository;
    }

    @RequestMapping(value = "/register", method = GET)
    public String showRegisterForm(Model model)
    {
        model.addAttribute(new Spitter());
        return "registerForm";
    }

    @RequestMapping(value = "/register", method = POST)
    public String saveRegister(@Valid Spitter spitter, Errors errors)
    {
        if (errors.hasErrors())
        {
            return "registerForm";
        }

        spitterRepository.save(spitter);
        // redirect: 重定向， 还支持 forward:
        return "redirect:/spitter/" + spitter.getName();
    }

    @RequestMapping(value = "/{name}", method = GET)
    public String showSpitterProfile(@PathVariable String name, Model model)
    {
        model.addAttribute(spitterRepository.findByName(name));
        return "profile";
    }
}
